<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Model\Album;
use Encore\Admin\Form;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Symfony\Component\HttpFoundation\RedirectResponse;

class AlbumController extends Controller
{

    public function index(Content $content)
    {
        $form = new Form(new Album);

        $album = Album::query()->first();

        $form->text('user_name', '用户名')
            ->default($album->user_name)
            ->rules('required', [
                'required' => '请输入用户名'
            ]);
        $form->text('password', '密码')
            ->default($album->password)
            ->rules('required', [
                'required' => '请输入密码'
            ]);

        $form->footer(function ($footer) {

            // 去掉`重置`按钮
            $footer->disableReset();

            // 去掉`查看`checkbox
            $footer->disableViewCheck();

            // 去掉`继续编辑`checkbox
            $footer->disableEditingCheck();

            // 去掉`继续创建`checkbox
            $footer->disableCreatingCheck();

        });

        $form->tools(function (Form\Tools $tools) {
            // 去掉`列表`按钮
            $tools->disableList();
            // 去掉`删除`按钮
            $tools->disableDelete();
            // 去掉`查看`按钮
            $tools->disableView();
        });

        $form->setTitle("相册登录密码管理");
        $form->setAction(config('admin.route.prefix') . '/album/save');

        return $content->row($form);
    }


    /**
     *  更新数据
     *
     * @param Request $request
     * @return RedirectResponse
     */
    public function save(Request $request)
    {

        $validator = Validator::make($request->all(), [
            'user_name' => 'required',
            'password' => 'required',
        ], [
            'user_name.required' => '请输入用户名',
            'password.required' => '请输入密码'
        ]);

        if ($validator->fails()) {
            return back()->withErrors($validator)
                ->withInput();
        }

        if (!$album = Album::query()->first()) {
            $album = new Album();
        }

        $album->user_name = $request->get('user_name');
        $album->password = $request->get('password');


        if ($album->save() !== false) {
            admin_toastr("操作成功", "success", ['timeOut' => 5000]);
            return back();
        }
        admin_toastr("操作失败", "warning", ['timeOut' => 5000]);
        return back();
    }

}
